package com.jdk.learn.thread;

/**
 * 生产消费者问题
 */
public class ProductAndConsumer03 {
    public static void main(String[] args) {
        User user = new User();
        Product03 product = new Product03(user);
        Consumer03 consumer = new Consumer03(user);
        product.start();
        consumer.start();
    }
}

class Product03 extends Thread {
    private User user;

    public Product03(User user) {
        this.user = user;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (user) {
                try {
                    if (user.flag) {
                        user.wait();
                    }
                    if (count == 0) {
                        user.setUserName("老黄");
                        user.setAge(20);
                    } else {
                        user.setUserName("老赵");
                        user.setAge(50);
                    }
                    count = (count + 1) % 2;
//            System.out.println("count:"+count);
                    user.flag = true;
                    user.notify();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Consumer03 extends Thread {
    private User user;

    public Consumer03(User user) {
        this.user = user;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (user) {
            try {
                if (!user.flag) {
                    user.wait();
                }
                System.out.println(user);
                user.flag = false;
                user.notify();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            }
        }
    }
}
